﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using deckAnalyser.Support;
using deckAnalyser.Domain;

namespace deckAnalyser.Controls
{
  public partial class CardsetViewControl : UserControl
  {
    private Collection collection = null;
    public Collection Collection
    {
      get { return collection; }
      set { collection = value; }
    }


    public CardsetViewControl()
    {
      InitializeComponent();


      ToolStripMenuItem tsiNameFilter = new ToolStripMenuItem("Name Filter", default(Image), (s, e) => changeFilter(s)) { Tag = filterTypeEnum.NameFilter };
      ToolStripMenuItem tsiTextFilter = new ToolStripMenuItem("Text Filter", default(Image), (s, e) => changeFilter(s)) { Tag = filterTypeEnum.TextFilter };
      ToolStripMenuItem tsiTypeFilter = new ToolStripMenuItem("Type Filter", default(Image), (s, e) => changeFilter(s)) { Tag = filterTypeEnum.TypeFilter };
      tsddbtnFilterType.DropDown.Items.Add(tsiNameFilter);
      tsddbtnFilterType.DropDown.Items.Add(tsiTextFilter);
      tsddbtnFilterType.DropDown.Items.Add(tsiTypeFilter);
      changeFilter(tsiNameFilter);

      dgv_cardset.KeyDown += new KeyEventHandler(dgv_cardset_KeyDown);

      dgv_cardset.DoubleClick += new EventHandler(dgv_cardset_DoubleClick);


      UpdateGrid();
    }

    void dgv_cardset_DoubleClick(object sender, EventArgs e)
    {
     
    }

    void dgv_cardset_KeyDown(object sender, KeyEventArgs e)
    {
      if (dgv_cardset.CurrentCell != null)
      {
        if (Char.IsLetterOrDigit((char)e.KeyValue) || e.KeyCode == Keys.Space)
        {
          if (e.Shift)
            FilterValue = filterValue + (Char)e.KeyValue;
          else
            FilterValue = filterValue + ((Char)e.KeyValue).ToString().ToLower();
        }
        else if (e.KeyCode == Keys.Back)
        {
          if (!String.IsNullOrEmpty(filterValue))
          {
            FilterValue = filterValue.Remove(FilterValue.Length - 1, 1);
          }
        }
        else if ((char)e.KeyValue == '\'')
        {
          FilterValue = FilterValue + (Char)e.KeyValue;
        }
        else if (e.KeyCode == Keys.Enter)
        {
          FilterValue = "";
        }
      }
      else
      {
        if (e.KeyCode == Keys.Back)
        {
          if (!String.IsNullOrEmpty(filterValue))
          {
            FilterValue = FilterValue.Remove(FilterValue.Length - 1, 1);
          }
        }
        else if (e.KeyCode == Keys.Enter)
        {
          FilterValue = "";
        }
      }
    }

    enum filterTypeEnum { NameFilter, TextFilter, TypeFilter };
    private filterTypeEnum filterType;
    private void changeFilter(object sender)
    {
      ToolStripMenuItem source = sender as ToolStripMenuItem;
      tsddbtnFilterType.Text = source.Text;
      filterType = (filterTypeEnum)source.Tag;
      FilterValue = "";
    }


    private String filterValue = "";
    public String FilterValue
    {
      set { filterValue = value; setFilter(); }
      get { return filterValue; }
    }

    private void setFilter()
    {
      if (String.IsNullOrEmpty(filterValue))
      {
        bs.Filter = null;
      }
      else
      {
        if (filterType == filterTypeEnum.NameFilter)
          bs.Filter = "[Card Name] like '%" + filterValue + "%'";
        else if (filterType == filterTypeEnum.TypeFilter)
          bs.Filter = "[Type] like '%" + filterValue + "%'";
        else if (filterType == filterTypeEnum.TextFilter)
          bs.Filter = "[Text] like '%" + filterValue + "%'";
      }

      tsslFilterValue.Text = "[" + filterValue + "]";
    }



    private BindingSource bs = new BindingSource();
    public void UpdateGrid()
    {
      if (!DBWrapper.IsOpen) return;

      DataTable dt = DBWrapper.GetDataTable(
            "SELECT c.name  AS 'Card Name'"+
            ",c.cost      AS 'Cost'"+
            ",c.type      AS 'Type'"+
            ",sc.rarity    AS 'Rarity'"+
            ",c.text       AS 'Text'"+
            ",0           AS 'Have'"+
            "FROM master.cards c"+
            "join master.setcards sc on sc.cardname = c.name"
      );

      //bs.Filter = filter;
      bs.DataSource = dt;
      dgv_cardset.DataSource = bs;

      dgv_cardset.AllowUserToAddRows = false;
      dgv_cardset.AllowUserToDeleteRows = false;
      dgv_cardset.MultiSelect = false;
      dgv_cardset.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;

      dgv_cardset.Columns["Card Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
      dgv_cardset.Columns["Have"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

      for (int i = 0; i < dt.Columns.Count; i++)
      {
        if (dgv_cardset.Columns[i].Name == "Card Name" || dgv_cardset.Columns[i].Name == "Have")
          dgv_cardset.Columns[i].Visible = true;
        else
          dgv_cardset.Columns[i].Visible = false;

        dgv_cardset.Columns[i].ReadOnly = true;
      }

      System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
      System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();

      dataGridViewCellStyle1.ForeColor = System.Drawing.Color.Black;
      dataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.LightGray;
      dataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.Black;
      dgv_cardset.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;

      dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
      dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window;
      dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Black;
      dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.LightGray;
      dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.Black;
      dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
      dgv_cardset.DefaultCellStyle = dataGridViewCellStyle2;

      dgv_cardset.RowEnter += new DataGridViewCellEventHandler(dataGridView_RowEnter);
      dgv_cardset.RowPrePaint += new DataGridViewRowPrePaintEventHandler(dataGridView_RowPrePaint);

    }

    public String CurrentCard
    {
      get
      {
        DataGridViewRow currentRow = dgv_cardset.CurrentRow;

        if (currentRow != null)
          return currentRow.Cells["Card Name"].Value as String;

        return null;
      }
    }

    public void Clear()
    {
    }

    private CardDetailsControl cardDetailsControl = null;
    public CardDetailsControl CardDetailsControl
    {
      get { return cardDetailsControl; }
      set { cardDetailsControl = value; }
    }

    private void dataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
    {
      UpdateCardDetailsControl(e.RowIndex);
    }

    private void dataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
      //if (dgv_cardset["Object", e.RowIndex].Value is Card)
      //{
      //  Card card = dgv_cardset["Object", e.RowIndex].Value as Card;
      //}
      //else
      //{
      //  dgv_cardset.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.SteelBlue;
      //  dgv_cardset.Rows[e.RowIndex].DefaultCellStyle.Font = new Font(FontFamily.GenericSansSerif, 10);
      //}

      //DataGridView dgv = (DataGridView)sender;
      //long have = (Int64)(dgv.Rows[e.RowIndex].Cells["Have"].Value);
      //long count = (Int64)(dgv.Rows[e.RowIndex].Cells["Count"].Value);


      //if (have < count)
      //{
      //  dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
      //  dgv.Rows[e.RowIndex].DefaultCellStyle.SelectionForeColor = Color.Red;
      // }
    }

    private void UpdateCardDetailsControl(int row)
    {
      if (row < dgv_cardset.Rows.Count)
      {
        if (cardDetailsControl != null)
        {
          cardDetailsControl.CardName = dgv_cardset["Card Name", row].Value as String;
          cardDetailsControl.CardCost = dgv_cardset["Cost", row].Value as String;
          cardDetailsControl.CardType = dgv_cardset["Type", row].Value as String;
          cardDetailsControl.CardSet = "";
          cardDetailsControl.CardRarity = dgv_cardset["Rarity", row].Value as String;
          cardDetailsControl.CardText = dgv_cardset["Text", row].Value as String;

        }
      }
    }
  }
}
